import React from "react";
import styles from "./index.module.css";
import {connect, MapDispatchToPropsParam, MapStateToPropsParam} from 'react-redux'
import { UserActions } from "@src/store/actions/userActions";
import { AppState, AppThunkDispatch } from "@src/index";
import { UserCreators } from "@src/store/creators/userCreators";
import { UserState } from "@src/store/reducers/userReducer";
import Confirm from "../confirm";
import {history} from '@src/App'


interface States {
  isOpen:boolean
}

 class Header extends React.Component<Props,States> {

  constructor(props:Readonly<Props>){
    super(props)

    this.state={
      isOpen:false
    }

  }


  async componentDidMount(){
    await this.props.requestUserInfo()
  }
  render() {
    const {result,status} = this.props.userReducer.user
    const {clearUser} = this.props

      //检测用户信息是否渲染成功
    if(status!=='success') return 
    return (
   <>
      <div className={styles.header}>
        <div className={styles.logo}>
          <img src={require("@image/logo.png")} alt="极客园" />
        </div>
        <div className={styles.user}>
          <span>{result.name}</span>
          <button className="button is-ghost has-text-white" onClick={()=>{this.setState({isOpen:true})}}>退出</button>
        </div>
      </div>
      <Confirm isOpen={this.state.isOpen} close={()=>this.setState({isOpen:false})} content={'您确定要退出登录吗11'} onSureButtonClicked={()=>{
        //清空用户信息
        clearUser()
        //跳转到登录页
        history.push('/login')
      }}/>
   </>
    );
  }
}

interface StateProps{
  userReducer: UserState;
}
interface DispatchProps{
  //获取管理员信息
  requestUserInfo: ()=>Promise<UserActions.Actions>

  //清空用户信息
  clearUser:()=>UserActions.Actions
}
interface OwnProps{}

type Props = StateProps &  DispatchProps & OwnProps

const mapStateToProps:MapStateToPropsParam<StateProps,OwnProps,AppState> = (state) =>({
  userReducer:state.userReducer
})



const mapDispatchToProps:MapDispatchToPropsParam< DispatchProps,OwnProps> =(dispatch:AppThunkDispatch)=>({

    //获取管理员信息
    requestUserInfo:()=>dispatch(UserCreators.requestUserInfo()),
    //清空用户信息
    clearUser:()=>dispatch(UserCreators.clearUser())
})

export default connect(mapStateToProps,mapDispatchToProps)(Header)